<?php
/**
* Letterman Newsletter Component
* 
* @package Letterman
* @author Soeren
* @copyright Soeren Eberhardt <soeren@virtuemart.net>
*   (who just needed an easy and *working* Newsletter component for Mambo 4.5.1 and mixed up Newsletter and YaNC)
* @copyright Mark Lindeman <mark@pictura-dp.nl> 
*    (parts of the Newsletter component by Mark Lindeman; Pictura Database Publishing bv, Heiloo the Netherland)
* @copyright Adam van Dongen <adam@tim-online.nl>
*    (parts of the YaNC component by Adam van Dongen, www.tim-online.nl)
*    
* @copyright Philip Sylvain <contact@sphilip.com>
*  	(MVC refactorization and AJAX)
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*
*/

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

jimport('joomla.application.component.controller');

class LettermanControllerNewsletters extends JController
{
	/**
	 * Custom Constructor
	 */
	function __construct( $default = array() )
	{
		// Set a default view if none exists
		if ( ! JRequest::getCmd( 'view' ) ) {
			
			JRequest::setVar('view', 'newsletters' );
		}
		
		parent::__construct( $default );

		$this->registerTask( 'apply', 'save' );
		$this->registerTask( 'add', 'edit' );
	}
	
	
	function edit()
	{
		//create the view
		$view = & $this->getView('newsletters', 'html');
		
		// Get/Create the model
		$model = & $this->getModel('Newsletters');	

		if ( $model->checkout() ){
		
			// Push the model into the view (as default)
			$view->setModel($model, true);
			$view->display('form');
			
		} else {
			$this->cancel();
		}
		
	}
	
	function save()
	{
		// Check for request forgeries
		JRequest::checkToken() or die( 'Invalid Token' );
		
		$model = & $this->getModel('Newsletters');

		if ( false ===  $model->save() ) {
			
			$this->edit();
		    
		} else {
			
			$url = 'index.php?option=com_letterman&controller=newsletters' ;
			
		  	if ( 'apply' == $this->getTask() ) {
		  		
		  		$row =& $model->getRow();
		  		$url = $url . '&task=edit&id=' . $row->id ;
		  	}
		  	
		  	$msg = JText::_( 'Successfully saved newsletter' ) ;
		    $this->setRedirect( $url , $msg );
		}
	}
	
	function remove()
	{
		// Check for request forgeries
		JRequest::checkToken() or die( 'Invalid Token' );
		
		$model = & $this->getModel('Newsletters');
		
		if ( $model->remove() ) {
			
			$msg = JText::sprintf('Newsletter(s) successfully deleted', count($model->getCid()));
			$this->setRedirect( 'index.php?option=com_letterman&controller=newsletters', $msg );
			
		} else {
			
			$this->setRedirect( 'index.php?option=com_letterman&controller=newsletters' );
		}	
	}
	
	function unpublish()
	{
		$this->_publish(false);
	}
	
	function publish()
	{
		$this->_publish(true);
	}
	

	/**
	 * Cancel an edit operation
	 * @access public
	 * @return void
	 */
	function cancel()
	{
		$model = & $this->getModel('Newsletters');
		$row = & $model->getRow();
		$row->checkin();
		
		$this->setRedirect( 'index.php?option=com_letterman&controller=newsletters' );
	}
	
	function send()
	{	
		//$jsontest = '{"mailfrom":"contact@sphilip.com", "replyto":"contact@sphilip.com", "only_confirmed":true}';
		//$jsontest = '';
		$json = JRequest::getVar('json', '');
		$model = & $this->getModel('Newsletters');

		if(!empty($json)){
			
			require JPATH_COMPONENT_ADMINISTRATOR . DS. 'lib' . DS .'JSON.php' ;
			$document = & JFactory::getDocument();
			$document->setMimeEncoding('application/json') ;
			
			$jsonService = new Services_JSON(); 
			$post = $jsonService->decode($json);
			
			$response = & $model->send( $post );
			
			if ( empty($response->error) && $response->nextlimitstart >= $response->total){
				$response->message = JText::sprintf('TOTAL_SUBSCRIBERS_WHO_HAVE_RECEIVED_NEWSLETTER', $response->total );
			}
			
			echo $jsonService->encode($response) ;
			
		} else {
			//create the view and display form
			$config =& JFactory::getConfig();
			$view = & $this->getView('newsletters', 'html');
			$view->assign('mailfrom',  $config->getValue('mailfrom', ''));
			$view->assign('replyto',  $config->getValue('mailfrom', ''));
			$view->assign('only_confirmed', true); //subscribers must be confirmed by default
			$state = 0;
			
			if (!empty($_POST)){
				
				$post = new stdClass();
				$post->mailfrom = JRequest::getVar('mailfrom', '');
				$post->replyto = JRequest::getVar('replyto', '');
				$post->only_confirmed = JRequest::getVar('only_confirmed', false);
				$post->limitstart = JRequest::getVar('limitstart', 0);
				$post->textformat = JRequest::getVar('textformat', 0);
				$response = & $model->send( $post );
				
				if ( empty($response->error) ){
					$state = 1; //send ok
					$mainframe =& JFactory::getApplication();
					$msg = JText::sprintf('SUBSCRIBERS_WHO_HAVE_RECEIVED_NEWSLETTER',$response->nextlimitstart, $response->total );
					$mainframe->enqueueMessage( $msg );
				} else {
					$state = -1;
					JError::raiseWarning( 500, $response->error );
				}
				
				$view->assignRef('response', $response);
				$view->assign($post);
			}
			$view->assign('id', JRequest::getInt('id', 0));
			$view->assign('state',  $state);
			$view->display('send');
		}
	}
	
	function _publish($bool)
	{
		$model = & $this->getModel('Newsletters');
		
		if ( $model->publish($bool) ) {
			
			$state = $bool ? 'published' : 'unpublished' ;
			$msg = JText::sprintf('Newsletter(s) successfully '. $state , count($model->getCid()));
			$this->setRedirect( 'index.php?option=com_letterman&controller=newsletters', $msg );
			
		} else {
			
			$this->setRedirect( 'index.php?option=com_letterman&controller=newsletters' );
		}
	}
	
}

